#include "Timer.h"
#include "Trace.h"
#include "UAP.pb.h"
#include "GAP.pb.h"

namespace tsc
{
namespace common
{

using namespace ProtocolsCommon;
using namespace UserApplicationPart;
using namespace GatewayApplicationPart;

/*******************************************************************************
 *
 * Constructor
 *
 ******************************************************************************/
Timer::Timer(
        RequestHandler* pReqHandler,
        uint32_t        generatorId,
        unsigned int    timerId,
        TimerType_e     type) :
    mpReqHandler(pReqHandler),
	mGeneratorId(generatorId),
	mTimerId(timerId),
	mCancelTimerId(0),
	mType(type)
{

} // Timer::Timer

/*******************************************************************************
 *
 * Destructor
 *
 ******************************************************************************/
Timer::~Timer()
{

} // Timer::~Timer

void
Timer::start(unsigned long value)
{
    TimerExpired timerExpired;
    timerExpired.set_timerid(mTimerId);
    std::string encodedPdu;

    if(mType == TIMER_TYPE_UAP)
    {
        UapPdu uapPdu;
        uapPdu.set_connectionid(mGeneratorId);
        uapPdu.set_pdunumber(UAP_PDU_TIMER);
        uapPdu.set_pdu(timerExpired.SerializeAsString());

        uapPdu.SerializeToString(&encodedPdu);
    }
    else if(mType == TIMER_TYPE_GAP)
    {
        GapPdu gapPdu;
        gapPdu.set_mgwid(mGeneratorId);
        gapPdu.set_pdunumber(GAP_PDU_TIMER);
        gapPdu.set_pdu(timerExpired.SerializeAsString());

        gapPdu.SerializeToString(&encodedPdu);
    }
    else
    {
        TRACE_ERROR(STR("Unknown timer type=%u", mType));
    }

    Message* pMessage = new Message(encodedPdu.data(),
                                    encodedPdu.size(),
                                    0); // not important

    mCancelTimerId = mpReqHandler->startTimer(pMessage, value);
}

void
Timer::cancel()
{
    if(mCancelTimerId != 0)
    {
        mpReqHandler->cancelTimer(mCancelTimerId);
    }
}

} // namespace common
} // namespace tsc
